// import TableFilterMixin from '@/mixins/TableFilterMixin'
import { Component } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'

import { Button } from 'ant-design-vue'
import { RedoOutlined, DownloadOutlined } from '@ant-design/icons-vue'

import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FormItemDto } from '@/components/low-code/types'
import { getDailyInsuranceMaterials,getSaleList, getInsuranceCompanyList, getDayInsuranceCount,getDayInsuranceCaseList, exportDailyInsuranceCaseList, getMaterialInsureCompany } from '@/api/insurance/period/index'
import type { LongInsuranceCaseListDto, InsuraceSaleDto, InsuranceCountDto, DayInsuranceCaseDto,ReportCaseResultDto, PeriodInsuranceMaterialsDto, InsuranceMaterialsFileDto } from '@/api/insurance/period/types'
import { getDaliyInsuranceCompanyList } from '@/api/insurance/company/index'
import type { InsuranceCompanyDto } from '@/api/insurance/company/types'
// import type { DictionaryDto } from '@/api/types'
import SetInfoPop from '../components/SetInfoPop'
import {
    type VxeGridPropTypes,
    type VxeTableDataRow,
    type VxeColumnSlotTypes,
} from 'vxe-table'
import TableDetail from '../components/TableDetail'
import { h, ref } from 'vue'
import { downloadFile, getCompanyListByName } from '@/utils/util'
import SetMaterialPop from '../components/SetMaterial'
import AddDailyClaimsPop from '../components/AddDailyClaimsPop'
import userStore from '@/stores/user'
import { ClaimPeriodStatusCnEnum, getKeyToEnum, HurtStatusCnEnum, MaterialStatusCnEnum } from '@/const/enum'
import DrawerDetail from '../components/DrawerDetail'
import type { FilterDto } from '@/render/FilterRender'

@Component
export class DailyInsuranceView extends TableRender {
    insureCompanyList = [] as string[]
    showAddClaims=false
    showSetMaterialInfo = false
    insuranceMaterialInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    previewList = [] as PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]
    showSetInfo = false
    insuranceBasicInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    // tabDetail = ref() as any
    noFilterPadding = true
    isDelState = true
    showDrawerDetail = false

    dayInsuranceCount = {} as InsuranceCountDto
    insureData = [
        { title: '案件总数', key:'totalReportCaseCount'  },
        { title: '待理赔', key:'totalClaimsPendingCount'  },
        { title: '已确认金额', key:'totalNotarizePriceCount'  },
        { title: '已结案', key:'totalSettleLawsuitCount'  },
        { title: '撤案/驳回', key:'totalRejectCount'  },
        { title: '已理赔金额', key:'totalFinalMoney'  },
        { title: '预估金额', key:'totalEstimateMoney'  },
    ] as { title: string, key: string }[]

    filterConfig() {
        return {
            companyName: {
                name: '客户名称',
                element: 'autoComplete',
                class: 'w-full',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            insureCompanyType: {
                name: '保司名称',
                element: 'select',
                value: '',
                options: [],
            },
            salesId: {
                name: '所属商务',
                element: 'select',
                placeholder: '请输入后选择',
                remote: true,
                options: [],
                params: {
                    method: async (event: string) => {
                        if (event) {
                            const res = await getSaleList({ isSelectSale: 1, salesName: event })
                            this.filters.salesId.options = res.map(item => ({
                                label: item.saleName,
                                value: item.saleId
                            })
                            )
                        }
                    }
                }
            },
            outDangerUserName: {
                name: '出险人姓名',
                element: 'input'
            },
            serveCompanyId: {
                name: '派遣单位',
                element: 'select',
                placeholder: '请输入后选择',
                optionsType: 'serveCompany'
            },
            outDangerIdCardNo: {
                name: '出险人身份证',
                element: 'input'
            },
            outDangerPhone: {
                name: '出险人手机号',
                element: 'input'
            },
            reportPhone: {
                name: '报案人手机号',
                element: 'input'
            },
            reportStatus: {
                name: '处理状态',
                element: 'select',
                options: getKeyToEnum(ClaimPeriodStatusCnEnum)
            },
            uploadStatus: {
                name: '材料状态',
                element: 'select',
                options: getKeyToEnum(MaterialStatusCnEnum, true)
            },
            hurtStatus: {
                name: '是否骨折',
                element: 'select',
                options: getKeyToEnum(HurtStatusCnEnum)
            },
            dateRange: {
                name: '出险日期',
                element: 'datetime',
                type: 'daterange',
                value: '',
                params: {
                    valueFormat: 'YYYY-MM-DD'
                }
            },
        } as FilterDto
    }

    tableColumnConfigOld = () => [
        {
            title: '操作',
            width: 50,
            params: {
                buttons: [
                    {
                        text: '设置',
                        event: (row) => this.onOpenSetInfo(row)
                    },
                    // {
                    //     text: '材料',
                    //     hidden: (row) => !this.canShowAdd(row.insurCompany),
                    //     event: (row) => this.onOpenSetMaterialInfo(row)
                    // }
                ]
            },
            slots: {
                default: 'tooltipButtons'
            }
        },
        {
            field: 'companyName',
            title: '公司名',
            width: 200,
            params: {
                event: (row: LongInsuranceCaseListDto<ReportCaseResultDto>) => {
                    this.handleShowDetal(row)
                }
            },
            slots: {
                default: 'clickable'
            }
        },
        {
            field: 'outDangerUserName',
            title: '出险人姓名',
        },
        {
            field: 'reportStatus',
            title: '处理状态',
            formatter: ({ row }) => {
                return ClaimPeriodStatusCnEnum[row.reportStatus]
            },
            params: {
                colors: {
                    0: 'blue-200',
                    1: 'yellow',
                    2: 'green',
                    3: 'red',
                    4: 'black-300',
                    5: 'cyan',
                    6: 'cyan'
                }
            },
            slots: {
                default: 'status'
            }
        },
        {
            field: 'serveCompanyName',
            title: '被派遣单位',
            width: 200
        },
        {
            field: 'insureCompanyName',
            title: '承保公司',
        },
        {
            field: 'reportPlan',
            title: '可用工种',
        },
        {
            field: 'estimateMoney',
            title: '预估金额'
        },
        {
            field: 'finalMoney',
            title: '最终金额'
        },
        {
            title: '所属业务员',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <div>
                            { row.sales.salesName}
                        </div>
                    )
                }
            }
        },
        {
            field: 'createTime',
            title: '录入时间',
            width: 160
        },
    ] as TableRenderColumnTypes<LongInsuranceCaseListDto<ReportCaseResultDto>>

    handleShowDetal(row: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        this.insuranceBasicInfo = row
        this.showDrawerDetail = true
    }
	
    canShowAdd(companyCode: string) {
        return this.insureCompanyList.some((i: string) => i === companyCode)
    } 
    hasPermission(prem: string) {
        const user = userStore()
        return user.permissions.some((i: string) => i === prem)
    }
	
    // 打开新增报案弹窗
    onOpenAddClaims() { 
        this.showAddClaims = true
    }
    // 导出报案列表
    async onExportDailyInsuranceCaseList() {
        const data = this.getFilters() as DayInsuranceCaseDto
        if (data.dateRange) { 
            data.beginOutDangerDate = data.dateRange[0] || ''
            data.endOutDangerDate = data.dateRange[1] || ''
            data.dateRange = undefined 
        }
        const url = await exportDailyInsuranceCaseList(data)
        downloadFile(url)
    }
    // 打开设置弹窗 并且存储信息
    onOpenSetInfo(data:LongInsuranceCaseListDto<ReportCaseResultDto>) { 
        this.showSetInfo = true
        this.insuranceBasicInfo = data
    }

    // 打开设置材料弹窗
    async onOpenSetMaterialInfo(event: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        // 获取理赔材料列表
        this.insuranceMaterialInfo = event 
        console.log(event, 'eventevent')
        await this.initDailyInsuranceMaterials()
        this.showSetMaterialInfo = true
    }
	
    // 获取理赔材料列表
    async initDailyInsuranceMaterials() {
        const result = await getDailyInsuranceMaterials({
            reportCaseId: Number(this.insuranceMaterialInfo.id),
            insureCompany: this.insuranceMaterialInfo.insureCompanyType,
        })
        this.previewList = result
        console.log(result, 'resultresultresult')
        return
    }

    // 获取日日保司列表
    async initDaliyInsuranceCompanyList() {
        const result = await getDaliyInsuranceCompanyList()

        console.log(333, this.filters.insureCompanyType)

        this.filters.insureCompanyType.options = result.map((item:InsuranceCompanyDto) => ({
            label: item.dictLabel,
            value: item.dictValue
        }))
    }
    // 获取日保险统计
    async initDayInsuranceCount() {
        const result = await getDayInsuranceCount()
        this.dayInsuranceCount = result
    }

    onLoadData(page: number, size: number, filters: DayInsuranceCaseDto) {
        if (filters.dateRange) { 
            filters.beginOutDangerDate = filters.dateRange[0] || ''
            filters.endOutDangerDate = filters.dateRange[1] || ''
            filters.dateRange = undefined 
        }
        return getDayInsuranceCaseList({
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }
    
    async created() {
        this.insureCompanyList = await getMaterialInsureCompany()
        this.initDayInsuranceCount()
        this.initDaliyInsuranceCompanyList()
		
    }

    insureDataDom() { 
        return (
            <div>
                <div class="flex items-center justify-between gap-6 my-12">
                    {this.insureData.map((item: { title: string; key: string }) => {
                        return (
                            <div class="flex-1 flex flex-col items-center pb-8">
                                <div class="text-base">{item.title}</div>
                                <div class="font-bold text-xl text-black-100">
                                    {this.dayInsuranceCount[item.key]}
                                </div>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }
	
    renderRightBtns() {
        return (
            <div class="flex flex-row-reverse mt-4">
                <Button icon={h(DownloadOutlined)} type="text" onClick={this.onOpenAddClaims}>
                    新增报案
                </Button>
                <Button icon={h(DownloadOutlined)} type="text" onClick={this.onExportDailyInsuranceCaseList}>
                    导出
                </Button>
            </div>
        )
    }

    render() {
        return (
            <div class="flex flex-col h-full overflow-hidden px-20px">
                {/* <div>
                    {this.renderFilter()}
                </div> */}
                {this.insureDataDom()}
                {super.render()}
                {/* { this.renderRightBtns() }
                {this.renderTable()}
                {this.renderPager()} */}
                {
                    <DrawerDetail
                        v-model:show={this.showDrawerDetail}
                        claimData={this.insuranceBasicInfo}
                        type="daily"
                    />
                }
                {
                    <SetInfoPop
                        v-model:show={this.showSetInfo}
                        basicInfo={this.insuranceBasicInfo}
                        onRefresh={this.reloadPage}
                        type='daily'
                    />
                }
                {/* {
                    <SetMaterialPop 
                        v-model:show={ this.showSetMaterialInfo }
                        previewList={this.previewList}
                        basicInfo={this.insuranceMaterialInfo}
                        type="daily"
                        onChange={this.initDailyInsuranceMaterials}
                    />
                } */}
                {
                    <AddDailyClaimsPop
                        v-model:show={this.showAddClaims}
                        onChange={this.reloadPage}
                    />
                }
            </div>
        )
    }
}

export default toNative<{}, {}>(DailyInsuranceView)